#include "privatechatwindow.h"
#include "ui_privatechatwindow.h"
#include <time.h>

PrivateChatWindow::PrivateChatWindow(const QString &friend_loginName, QWidget *parent) :
    QMainWindow(parent),
    m_ui(new Ui::PrivateChatWindow)
{
    m_ui->setupUi(this);

    setWindowTitle("Tunnel - "+friend_loginName);
    myFriend_loginName = friend_loginName;

    connect( m_ui->teMessage, SIGNAL(returnWithoutShiftPressed()), this, SLOT(on_teMessage_returnWithoutShiftPressed()) );
}

PrivateChatWindow::~PrivateChatWindow()
{
    delete m_ui;
}

void PrivateChatWindow::changeEvent(QEvent *e)
{
    QMainWindow::changeEvent(e);
    switch (e->type()) {
    case QEvent::LanguageChange:
        m_ui->retranslateUi(this);
        break;
    default:
        ;
    }
}

void PrivateChatWindow::on_pbSenden_clicked()
{
    if( m_ui->teMessage->toPlainText() == "" )
        return;

    addChatMessage("I", m_ui->teMessage->toPlainText()); // <--- Have to write clients nickname here instead of "I" <---

    emit sendMessageToFriend(myFriend_loginName, m_ui->teMessage->toPlainText());
    m_ui->teMessage->setText("");
}

void PrivateChatWindow::addChatMessage(const QString &from, const QString &message)
{
    time_t t;
    struct tm *ts;

    t = time(NULL);
    ts = localtime(&t);

    QString newLine = QString("[%1%2:%3%4] %5: %6").arg(ts->tm_hour < 10 ? "0" : "").arg(ts->tm_hour).
                                                    arg(ts->tm_min < 10 ? "0" : "").arg(ts->tm_min).
                                                    arg(from).
                                                    arg(message);

    m_ui->pteChat->appendPlainText(newLine);
}

void PrivateChatWindow::on_teMessage_returnWithoutShiftPressed()
{
    on_pbSenden_clicked();
}

void PrivateChatWindow::closeEvent(QCloseEvent *event)
{
    emit privateChatWindowClose(myFriend_loginName);
}
